package com.springcloud.security;

import com.springcloud.model.SysRole;
import com.springcloud.model.vo.UserVo;
import com.springcloud.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @program: springcloud
 * @description: 自定义的UserDetailsService
 * @author: paddy
 * @create: 2019-04-15 12:47
 **/
@Service
public class MyUserDetailsService implements UserDetailsService {


    @Autowired
    private ISysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserVo userVo = userService.selectVoByLoginName(username); // 查询用户
        if (userVo == null ) { // 如果没查询到返回错误
            throw new UsernameNotFoundException("用户名称错误！");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        Iterator<SysRole> iRole = userVo.getRolesList().iterator();
        while (iRole.hasNext()){ // 添加查询到的角色信息
            authorities.add(new SimpleGrantedAuthority(iRole.next().getName()));
        }
        return new User(userVo.getLoginName(), userVo.getPassword(),authorities);
    }
}
